import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

void main() {
  runApp(MyApp());
}

/// 1. Widget在Flutter中的地位
/// Widget是Flutter的核心构建块，所有的UI元素都是Widget，包括布局、按钮、文本等。
/// Widget描述了UI的外观，但不直接绘制内容，真正的绘制由Element和RenderObject完成。
///
/// 2. Flutter中的四棵树
/// - Widget树：描述UI结构和外观（声明式）
/// - Element树：Widget与RenderObject之间的桥梁，管理Widget的生命周期
/// - RenderObject树：负责布局和绘制
/// - Layer树：用于合成和渲染到屏幕
///
/// 3. StatelessWidget
/// 无状态组件，表示不可变的UI部分，创建后不会改变（如静态文本、图标等）
///
/// 4. StatefulWidget
/// 有状态组件，UI可以根据内部状态变化而变化（如计数器、表单等）
///
/// 5. Material与Cupertino
/// - Material：实现Material Design风格的组件（Android风格）
/// - Cupertino：实现iOS风格的组件（iOS风格）

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Widget 核心知识演示',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Widget 核心知识'),
        ),
        body: ListView(
          children: [
            ListTile(
              title: Text('1. Widget在Flutter中的地位'),
              subtitle: Text('Widget是Flutter UI的基本构建块，所有UI元素都是Widget。'),
            ),
            ListTile(
              title: Text('2. Flutter中的四棵树'),
              subtitle: Text(
                  'Widget树、Element树、RenderObject树、Layer树，分别负责描述、管理、绘制和渲染UI。'),
            ),
            ListTile(
              title: Text('Flutter四棵树结构图'),
              subtitle: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Text(
                  '''
Widget树
  ├─ MaterialApp
  │   └─ Scaffold
  │       ├─ AppBar
  │       └─ ListView
  │           ├─ ListTile
  │           ├─ ListTile
  │           └─ ...

Element树
  ├─ StatelessElement(MaterialApp)
  │   └─ StatefulElement(Scaffold)
  │       ├─ StatelessElement(AppBar)
  │       └─ StatelessElement(ListView)
  │           ├─ StatelessElement(ListTile)
  │           ├─ StatelessElement(ListTile)
  │           └─ ...

RenderObject树
  ├─ RenderView
  │   └─ RenderBox(MaterialApp)
  │       └─ RenderBox(Scaffold)
  │           ├─ RenderBox(AppBar)
  │           └─ RenderBox(ListView)
  │               ├─ RenderBox(ListTile)
  │               ├─ RenderBox(ListTile)
  │               └─ ...

Layer树
  ├─ RootLayer
  │   └─ ContainerLayer
  │       ├─ PictureLayer(AppBar)
  │       ├─ PictureLayer(ListView)
  │       └─ ...
''',
                  style: TextStyle(fontFamily: 'monospace', fontSize: 12),
                ),
              ),
            ),
            ListTile(
              title: Text('3. StatelessWidget示例'),
              subtitle: StatelessExample(),
            ),
            ListTile(
              title: Text('4. StatefulWidget示例'),
              subtitle: StatefulExample(),
            ),
            ListTile(
              title: Text('StatefulWidget示例'),
              subtitle: AdvancedStatefulExample(),
            ),
            ListTile(
              title: Text('StatefulWidget原理与演示'),
              subtitle: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8.0),
                child: FancyStatefulDemoGroup(),
              ),
            ),
            ListTile(
              title: Text('5. Material与Cupertino'),
              subtitle: Text('Material用于Android风格，Cupertino用于iOS风格。'),
            ),
            ListTile(
              title: Text('Material按钮示例'),
              subtitle: Builder(
                builder: (context) => MaterialButton(
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('你点击了 Material 按钮')),
                    );
                  },
                  color: Colors.blue,
                  child: Text('Material 按钮', style: TextStyle(color: Colors.white)),
                ),
              ),
            ),
            ListTile(
              title: Text('Cupertino按钮示例'),
              subtitle: Builder(
                builder: (context) => CupertinoExample(),
              ),
            ),
            ListTile(
              title: Text('弹出对话框示例'),
              subtitle: Builder(
                builder: (context) => ElevatedButton(
                  child: Text('显示对话框'),
                  onPressed: () {
                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        title: Text('普通对话框'),
                        content: Text('这是一个 Material 风格的对话框。'),
                        actions: [
                          TextButton(
                            child: Text('关闭'),
                            onPressed: () => Navigator.of(context).pop(),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// StatelessWidget 示例
class StatelessExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Text('我是StatelessWidget（无状态组件），内容不会变化。');
  }
}

/// StatefulWidget 示例
class StatefulExample extends StatefulWidget {
  @override
  _StatefulExampleState createState() => _StatefulExampleState();
}

class _StatefulExampleState extends State<StatefulExample> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Text('点击次数: $_counter'),
        IconButton(
          icon: Icon(Icons.add),
          onPressed: () {
            setState(() {
              _counter++;
            });
          },
        ),
      ],
    );
  }
}

/// StatefulWidget示例
class AdvancedStatefulExample extends StatefulWidget {
  @override
  _AdvancedStatefulExampleState createState() => _AdvancedStatefulExampleState();
}

class _AdvancedStatefulExampleState extends State<AdvancedStatefulExample> {
  int _counter = 0;
  Color _bgColor = Colors.amber[100]!;
  String _lifecycle = 'initState';
  List<String> _logs = [];

  @override
  void initState() {
    super.initState();
    _lifecycle = 'initState';
  }

  @override
  void didUpdateWidget(covariant AdvancedStatefulExample oldWidget) {
    super.didUpdateWidget(oldWidget);
    setState(() {
      _lifecycle = 'didUpdateWidget';
    });
  }

  @override
  void deactivate() {
    _lifecycle = 'deactivate: 组件从树中临时移除时调用';
    _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)}  $_lifecycle');
    if (_logs.length > 6) _logs.removeLast();
    super.deactivate();
  }

  @override
  void dispose() {
    _lifecycle = 'dispose: 组件永久移除时调用';
    _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)}  $_lifecycle');
    if (_logs.length > 6) _logs.removeLast();
    super.dispose();
  }

  void _increment() {
    setState(() {
      _counter++;
      _lifecycle = 'setState -> build';
    });
  }

  void _toggleColor() {
    setState(() {
      _bgColor = _bgColor == Colors.amber[100]! ? Colors.lightGreen[100]! : Colors.amber[100]!;
      _lifecycle = 'setState -> build';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: _bgColor,
      padding: EdgeInsets.all(8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('点击次数: $_counter', style: TextStyle(fontSize: 16)),
          Row(
            children: [
              ElevatedButton(
                onPressed: _increment,
                child: Text('加1'),
              ),
              SizedBox(width: 8),
              ElevatedButton(
                onPressed: _toggleColor,
                child: Text('切换背景色'),
              ),
            ],
          ),
          SizedBox(height: 8),
          Text('当前生命周期: $_lifecycle', style: TextStyle(fontSize: 12, color: Colors.grey[700])),
        ],
      ),
    );
  }
}

/// 更详细美观的StatefulWidget演示
class FancyStatefulDemo extends StatefulWidget {
  FancyStatefulDemo({Key? key}) : super(key: key);

  @override
  State<FancyStatefulDemo> createState() => _FancyStatefulDemoState();
}

class _FancyStatefulDemoState extends State<FancyStatefulDemo> {
  int _counter = 0;
  Color _bgColor = Colors.blue[50]!;
  String _lifecycle = 'initState';
  List<String> _logs = [];

  @override
  void initState() {
    super.initState();
    _addLog('initState: 初始化状态，只调用一次');
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _addLog('didChangeDependencies: 依赖发生变化时调用');
  }

  @override
  void didUpdateWidget(covariant FancyStatefulDemo oldWidget) {
    super.didUpdateWidget(oldWidget);
    _addLog('didUpdateWidget: 父组件重建时调用');
  }

  @override
  void deactivate() {
    _lifecycle = 'deactivate: 组件从树中临时移除时调用';
    _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)}  $_lifecycle');
    if (_logs.length > 6) _logs.removeLast();
    super.deactivate();
  }

  @override
  void dispose() {
    _lifecycle = 'dispose: 组件永久移除时调用';
    _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)}  $_lifecycle');
    if (_logs.length > 6) _logs.removeLast();
    super.dispose();
  }

  void _addLog(String log) {
    setState(() {
      _lifecycle = log;
      _logs.insert(0, '${DateTime.now().toIso8601String().substring(11, 19)}  $log');
      if (_logs.length > 6) _logs.removeLast();
    });
  }

  void _increment() {
    setState(() {
      _counter++;
      _addLog('setState: 计数+1，build重建');
    });
  }

  void _decrement() {
    setState(() {
      _counter--;
      _addLog('setState: 计数-1，build重建');
    });
  }

  void _toggleColor() {
    setState(() {
      _bgColor = _bgColor == Colors.blue[50]! ? Colors.pink[50]! : Colors.blue[50]!;
      _addLog('setState: 切换背景色，build重建');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 320,
      constraints: BoxConstraints(minHeight: 260),
      decoration: BoxDecoration(
        color: _bgColor,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Colors.blueAccent.withOpacity(0.2)),
        boxShadow: [
          BoxShadow(
            color: Colors.blueAccent.withOpacity(0.05),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      padding: EdgeInsets.all(20),
      margin: EdgeInsets.only(bottom: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '独立计数器卡片',
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.blue[800]),
          ),
          SizedBox(height: 4),
          Text(
            'Widget hashCode: ${widget.hashCode}\n'
            'State hashCode: ${this.hashCode}',
            style: TextStyle(fontSize: 12, color: Colors.blueGrey[700], fontFamily: 'monospace'),
          ),
          Divider(),
          Row(
            children: [
              IconButton(
                icon: Icon(Icons.remove_circle, color: Colors.redAccent),
                onPressed: _decrement,
                tooltip: '减1',
              ),
              Text(
                '$_counter',
                style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold, color: Colors.blue[900]),
              ),
              IconButton(
                icon: Icon(Icons.add_circle, color: Colors.green),
                onPressed: _increment,
                tooltip: '加1',
              ),
              SizedBox(width: 16),
              ElevatedButton.icon(
                onPressed: _toggleColor,
                icon: Icon(Icons.color_lens),
                label: Text('切换背景色'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue[100],
                  foregroundColor: Colors.blue[900],
                ),
              ),
            ],
          ),
          SizedBox(height: 8),
          Text(
            '当前生命周期事件：',
            style: TextStyle(fontSize: 14, color: Colors.blueGrey),
          ),
          Container(
            width: double.infinity,
            margin: EdgeInsets.symmetric(vertical: 4),
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.8),
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.blue[100]!),
            ),
            child: Text(
              _lifecycle,
              style: TextStyle(fontSize: 13, color: Colors.deepPurple),
            ),
          ),
          SizedBox(height: 4),
          Text(
            '生命周期调用日志（最新在上）：',
            style: TextStyle(fontSize: 13, color: Colors.blueGrey),
          ),
          Container(
            height: 70,
            padding: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.grey[50],
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.blue[50]!),
            ),
            child: ListView(
              children: _logs
                  .map((log) => Text(
                        log,
                        style: TextStyle(fontSize: 12, color: Colors.black87),
                      ))
                  .toList(),
            ),
          ),
        ],
      ),
    );
  }
}

/// 展示多个独立StatefulWidget实例
class FancyStatefulDemoGroup extends StatefulWidget {
  @override
  State<FancyStatefulDemoGroup> createState() => _FancyStatefulDemoGroupState();
}

class _FancyStatefulDemoGroupState extends State<FancyStatefulDemoGroup> {
  int _count = 1;

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _relationDiagram(),
        SizedBox(height: 12),
        Row(
          children: [
            ElevatedButton.icon(
              icon: Icon(Icons.add),
              label: Text('克隆一个新实例'),
              onPressed: () => setState(() => _count++),
            ),
            SizedBox(width: 12),
            Text('当前实例数：$_count', style: TextStyle(fontSize: 15, color: Colors.blueGrey)),
          ],
        ),
        SizedBox(height: 12),
        Wrap(
          spacing: 16,
          runSpacing: 16,
          children: List.generate(_count, (i) => FancyStatefulDemo(key: UniqueKey())),
        ),
      ],
    );
  }

  Widget _relationDiagram() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.indigo[50],
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.indigo[100]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('StatefulWidget/Element/State 关系图', style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold, color: Colors.indigo[900])),
          SizedBox(height: 6),
          Text(
            '''
StatefulWidget（配置数据/描述UI）
        │
        ▼
StatefulElement（桥梁/生命周期管理）
        │
        ▼
State（可变状态/业务逻辑）
''',
            style: TextStyle(fontFamily: 'monospace', fontSize: 13, color: Colors.indigo[800]),
          ),
          SizedBox(height: 4),
          Text(
            '每插入一个StatefulWidget到树中，都会生成独立的StatefulElement和State。\n'
            '下方每个“计数器卡片”都是独立的State实例，互不影响。',
            style: TextStyle(fontSize: 13, color: Colors.indigo[700]),
          ),
        ],
      ),
    );
  }
}

/// Cupertino 示例（需要引入cupertino库）
class CupertinoExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      child: Text('Cupertino 按钮'),
      color: CupertinoColors.activeBlue,
      onPressed: () {
        showCupertinoDialog(
          context: context,
          builder: (context) => CupertinoAlertDialog(
            title: Text('提示'),
            content: Text('你点击了 Cupertino 按钮'),
            actions: [
              CupertinoDialogAction(
                child: Text('确定'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          ),
        );
      },
    );
  }
}